package com.lanzhou.yuanfen.config;

import com.lanzhou.yuanfen.security.MyUserDetails;
import com.lanzhou.yuanfen.security.SocialDetails;
import com.lanzhou.yuanfen.security.token.QQAuthenticationToken;
import com.lanzhou.yuanfen.sys.entity.User;
import com.lanzhou.yuanfen.sys.mapper.UserMapper;
import com.lanzhou.yuanfen.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Administrator
 */
@Slf4j
public class Token {

    /**
     * 获取用户信息
     *
     * @return
     */
    public static User getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        User token = null;
        log.info("当前用户认证信息为: ", authentication);
        if (authentication instanceof QQAuthenticationToken) {
            if (authentication.getPrincipal() instanceof SocialDetails) {
                UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
                String openId = ((QQAuthenticationToken) authentication).getOpenId();
                token = userMapper.selectUserByOpenId(openId);
            } else if (authentication.getPrincipal() instanceof MyUserDetails) {
                token = getMyUserDetailsUser(authentication);
            }
            log.info("现在是QQ系统用户: ", token);
        } else {
            token = getMyUserDetailsUser(authentication);
            log.info("现在是其他登入: ", authentication);
        }
        return token;
    }

    /**
     * 获取MyUserDetails中的用户信息
     *
     * @param authentication
     * @return
     */
    private static User getMyUserDetailsUser(Authentication authentication) {
        User token = null;
        MyUserDetails principal = (MyUserDetails) authentication.getPrincipal();
        if (principal != null) {
            token = principal.getUser();
        }
        return token;
    }


    /*if (authentication instanceof EmailAuthenticationToken) {
        String email = ((EmailAuthenticationToken) authentication).getEmail();
        token = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));
    }
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
        String username = authentication.getName();
        token = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }*/


}
